package com.dayanxs.Service;

import com.dayanxs.Utils.AESCryptoUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserService {

    private final JdbcTemplate jdbcTemplate;

    public UserService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public ResponseEntity<?> handleLogin(String username, String password) {
        try {
            String sql = "SELECT COUNT(*) FROM user WHERE username = ? AND password = ?";
            int count = jdbcTemplate.queryForObject(sql, new Object[]{username, password}, Integer.class);

            if (count == 1) {
                String combined = username + "." + password;
                String encryptedToken = AESCryptoUtil.encrypt(combined);

                Map<String, String> response = new HashMap<>();
                response.put("token", encryptedToken);

                return ResponseEntity.ok(response);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "账号或者密码输入错误！");

                return ResponseEntity.status(201).body(errorResponse);
            }
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Encryption or database error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> getUserAndNovelInfo(String authorization) {
        // 检查 Authorization 头部
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return ResponseEntity.status(201).body(Map.of("message", "Bearer token missing or invalid"));
        }

        // 从 Authorization 中提取 Bearer 令牌
        String userToken = authorization.substring(7); // 去掉 "Bearer " 前缀

        if (userToken.isEmpty()) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "userToken为空！");
            return ResponseEntity.status(201).body(errorResponse);
        }

        try {
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\."); // 分割用户名和密码

            if (parts.length != 2) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "无效的token格式");
                return ResponseEntity.status(201).body(errorResponse);
            }

            String username = parts[0];

            Map<String, Object> user = jdbcTemplate.queryForMap(
                    "SELECT * FROM user WHERE username = ?",
                    new Object[]{username}
            );

            if (user == null || user.isEmpty()) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户未找到！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            Integer userId = (Integer) user.get("id");

            // 查询用户的小说信息
            List<Map<String, Object>> novels = jdbcTemplate.queryForList(
                    "SELECT * FROM novel WHERE novel_authorID = ? order by novel_id desc",
                    new Object[]{userId}
            );

            Map<String, Object> response = new HashMap<>();
            response.put("userInfo", user);
            response.put("novelInfo", novels);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Decryption or query error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> handleRegistration(Map<String, String> userInfo) {
        String username = userInfo.get("username");
        String password = userInfo.get("password");

        if (username == null || password == null) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "必须传入用户名和密码！");
            return ResponseEntity.status(201).body(errorResponse);
        }

        if (password.length() < 6) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "密码至少六位！");
            return ResponseEntity.status(201).body(errorResponse);
        }

        try {
            String checkSql = "SELECT COUNT(*) FROM user WHERE username = ?";
            int userCount = jdbcTemplate.queryForObject(checkSql, new Object[]{username}, Integer.class);

            String sql2 = "SELECT COUNT(*) FROM admin WHERE username = ?";      //查询是否和admin表重名
            int adminCount = jdbcTemplate.queryForObject(sql2, new Object[]{username}, Integer.class);

            int count = userCount + adminCount;

            if (count > 0) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户名已存在！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            String insertSql = "INSERT INTO user (`id`, `nickname`, `username`, `password`, `introduce`, `isAuthor`) VALUES (NULL, ?, ?, ?, '还没有介绍...', 0)";
            jdbcTemplate.update(insertSql, username, username, password);

            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "注册成功！");

            return ResponseEntity.status(200).body(successResponse);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Database error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> handleDeleteUser(int id, String authorization) {
        try {
            // 从 Authorization 中提取 Bearer 令牌
            String adminToken = getToken(authorization); // 去掉 "Bearer " 前缀

            if (!isAdmin(adminToken)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "非管理员禁止操作！");
                return ResponseEntity.status(201).body(errorResponse);
            }
            String haveNovelSql = "SELECT COUNT(*) FROM `novel` WHERE novel_authorID = ?";
            int rowsHave = jdbcTemplate.queryForObject(haveNovelSql, new Object[]{id}, Integer.class);
            if (rowsHave > 0) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "请先清空该用户下所有小说才可以删除！");
                return ResponseEntity.status(201).body(errorResponse); // 使用HttpStatus枚举而不是原始状态码
            }


            String deleteSql = "DELETE FROM user WHERE id = ?";
            int rowsAffected = jdbcTemplate.update(deleteSql, id);

            if (rowsAffected > 0) {
                Map<String, String> successResponse = new HashMap<>();
                successResponse.put("message", "用户删除成功！");
                return ResponseEntity.ok(successResponse);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户没有找到！");
                return ResponseEntity.status(201).body(errorResponse);
            }

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Decryption or query error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> updateUser(String authorization, Map<String, String> userDetails) {
        try {
            // 检查 Authorization 头部
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                return ResponseEntity.status(201).body(Map.of("message", "Bearer token missing or invalid"));
            }

            // 从 Authorization 中提取 Bearer 令牌
            String userToken = authorization.substring(7); // 去掉 "Bearer " 前缀

            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\."); // 分割用户名和密码

            if (parts.length != 2) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "无效的token格式！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            String username = parts[0];
            String password =  parts[1];
            String nickname = userDetails.get("nickname");
            String introduce = userDetails.get("introduce");

            String newpassword = userDetails.get("password");
            // 如果 password 为 null 或空字符串，不报错
            /*if (newpassword == null || newpassword.trim().isEmpty()) {
                newpassword = password;
            }*/

            if (nickname == null || introduce == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "昵称和介绍必须填写！");
                return ResponseEntity.status(201).body(errorResponse);
            }
            String updateSql;
            int rowsAffected;
            if(newpassword.isEmpty()){
                updateSql = "UPDATE user SET nickname = ?, introduce = ? WHERE username = ?";
                rowsAffected = jdbcTemplate.update(updateSql, nickname, introduce, username);
            }else{
                updateSql = "UPDATE user SET nickname = ?, introduce = ?, password = ? WHERE username = ?";
                rowsAffected = jdbcTemplate.update(updateSql, nickname, introduce, newpassword, username);
            }

            if (rowsAffected > 0) {
                Map<String, String> successResponse = new HashMap<>();
                successResponse.put("message", "用户信息更新成功！");
                return ResponseEntity.ok(successResponse);
            } else {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "用户没有找到！");
                return ResponseEntity.status(201).body(errorResponse);
            }

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Decryption or query error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }

    public ResponseEntity<?> changePassword(String userToken, Map<String, String> passwords) {
        try {
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\."); // 分割用户名和密码

            if (parts.length != 2) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "无效的token格式！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            String username = parts[0];
            String oldPassword = passwords.get("oldPassword");
            String newPassword = passwords.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "新旧密码必须填写！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            if (newPassword.length() < 6) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "新密码长度至少为六位！");
                return ResponseEntity.status(201).body(errorResponse);
            }

            String querySql = "SELECT password FROM user WHERE username = ?";
            String existingPassword = jdbcTemplate.queryForObject(querySql, new Object[]{username}, String.class);

            if (!oldPassword.equals(existingPassword)) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "填写的旧密码不正确！");
                return ResponseEntity.status(403).body(errorResponse);
            }

            String updateSql = "UPDATE user SET password = ? WHERE username = ?";
            jdbcTemplate.update(updateSql, newPassword, username);

            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("message", "密码更新成功！");
            return ResponseEntity.ok(successResponse);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Decryption or query error");
            return ResponseEntity.status(201).body(errorResponse);
        }
    }
    public ResponseEntity<?> searchUsers(String authorization,String userName,Integer type) {
        try {
            String adminToken = getToken(authorization);
            String sql;
            if(type == 1){          //username 非管理员搜索接口
                sql = "SELECT id,nickname,username,introduce,isAuthor FROM user WHERE username LIKE ?";
            }else if(type == 2){
                sql = "SELECT id,nickname,username,introduce,isAuthor FROM user WHERE nickname LIKE ?";
            }else{
                sql = "SELECT id,nickname,username,introduce,isAuthor FROM user WHERE username = ?"; //精准搜索
            }

            if(isAdmin(adminToken)){
                if(type == 1){          //username  管理员搜索接口
                    sql = "SELECT * FROM user WHERE username LIKE ?";
                }else if(type == 2){
                    sql = "SELECT * FROM user WHERE nickname LIKE ?";
                }else{
                    sql = "SELECT * FROM user WHERE username = ?";
                }
            }
            List<Map<String, Object>> users = null;
            if(type == 1||type == 2){
                users = jdbcTemplate.queryForList(sql, new Object[]{"%" + userName + "%"});
            }else{
                users = jdbcTemplate.queryForList(sql, new Object[]{userName});
            }


            if (users.isEmpty()) {
                return ResponseEntity.ok(Collections.emptyList());
            }
            return ResponseEntity.ok(users);

        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "Error searching novels: " + e.getMessage());
            return ResponseEntity.status(201).body(errorResponse);
        }
    }
    private String getToken(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return "";
        }
        // 从 Authorization 中提取 Bearer 令牌
        return authorization.substring(7);
    }
    private boolean isAdmin(String adminToken) {
        String decryptedData = null;
        try {
            decryptedData = AESCryptoUtil.decrypt(adminToken);
        } catch (Exception e) {
            return false;
        }
        String[] parts = decryptedData.split("\\."); // 分割用户名和密码

        if (parts.length != 2) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "无效的token格式");
            return false;
        }

        String username = parts[0];

        try {
            // 查询用户是否是管理员
            String sql = "SELECT 1 FROM admin WHERE username = ?";
            jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);
            // 如果查询成功执行到这里，说明用户是管理员
            return true;
        } catch (EmptyResultDataAccessException e) {
            // 用户不存在于admin表中，返回false
            return false;
        } catch (Exception e) {
            return false;
        }
    }

}
